package com.tfy.liquor.controller;

import com.tfy.liquor.bean.Result;
import com.tfy.liquor.bean.UserInfo;
import com.tfy.liquor.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/registeredVerification")
    public Result registeredVerification(HttpSession session, UserInfo userInfo) {
        try {
            Thread.sleep(500);
        } catch (Exception ignored) {
            System.err.println("用户注册出错！");
        }
        // 检查该手机号码是否注册,返回true表示已经注册
        if (userInfoService.checkUserInfoRegistrationStatus(userInfo)) {
            return new Result().error("该账户已经注册！");
        }
        // 注册
        if (userInfoService.addUserInfo(userInfo)) {
            return new Result().ok("注册成功！");
        }
        return new Result().error("注册失败！");
    }

    /**
     * 用户登录验证
     *
     * @param userInfo
     * @param session
     * @return
     */
    @RequestMapping("/loginVerification")
    public Result loginVerification(HttpSession session, UserInfo userInfo) {
//        System.err.println("用户登录");
//        System.err.println(userInfo);
        try {
            Thread.sleep(500);
        } catch (Exception ignored) {
            System.err.println("用户登录出错！");
        }
//        System.err.println(userInfo);
        return userInfoService.userInfoLogin(userInfo);
    }

    /**
     * 绑定推荐关系
     *
     * @param userInfo
     * @return
     */
    @RequestMapping("/bindRecommendRelationship")
    public Result bindRecommendRelationship(UserInfo userInfo) {
        if (null == userInfo || null == userInfo.getUserId() || null == userInfo.getParentId()) {
            // 返回参数错误
            return new Result().bad_CodeIsNull();
        }
        // 如果传入的id是自己的id，则提示错误
        if (userInfo.getUserId().equals(userInfo.getParentId())) {
            return new Result().error("不能传入自己的ID！");
        }
        // 绑定关系
        if (userInfoService.bindRecommendRelationship(userInfo)) {
            return new Result().ok("绑定成功！");
        }
        return new Result().error("绑定失败！");
    }

    @RequestMapping("/getLowerUserInfoByUserId")
    public Result getLowerUserInfoByUserId(Long userId) {
        if (null == userId || userId < 0) {
            return new Result().bad_CodeIsNull();
        }
        return new Result(userInfoService.getLowerUserInfoByUserId(userId)).ok();
    }

    /**
     * 测试方法
     *
     * @param session
     * @param userInfo
     * @return
     */
    @RequestMapping("/test")
    public Result test(HttpSession session, UserInfo userInfo) {
        // 保存用户信息到session中
        return new Result().ok("数据访问成功！");
    }


}
